using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SpeedSearch
{

    public static class FileHelper
    {

        /// <summary>
        /// Retorna os diretórios das versões
        /// </summary>
        /// <param name="devRoot">Caminho do diretório dev</param>
        /// <returns></returns>
        public static Dictionary<string, BrancheInfo> GetVersions(string devRoot)
        {
            Dictionary<string, BrancheInfo> versions = new Dictionary<string, BrancheInfo>(StringComparer.InvariantCultureIgnoreCase);

            string[] dirs = Directory.GetDirectories(devRoot);

            foreach (var dir in dirs)
            {
                BrancheInfo ver = new BrancheInfo();
                string dirName = Path.GetFileName(dir).ToString();
                
                string path = null;
                int maxLevel = 0;
                if (dirName == "DML")
                {
                    path = Path.Combine(dir, @"SIS");
                    maxLevel = 2;
                }
                else if (dirName.StartsWith("SIS."))
                {
                    path = devRoot;
                    maxLevel = 1;
                }

                if (path != null)
                {
                    string[] vdirs = Directory.GetDirectories(path);
                    foreach (string vdir in vdirs)
                        GetVersions(vdir, versions, 1, maxLevel);
                }
            }
            return versions;
        }

        public static void GetVersions(string path, Dictionary<string, BrancheInfo> versions, int level, int maxLevel)
        {
            string[] dirs = Directory.GetDirectories(path);
            foreach (string dir in dirs)
            {
                string dirName = Path.GetFileName(dir);
                string verName = Util.GetVersionName(dirName);
                if (verName != null)
                {
                    string systemName = dirName.Substring(0, dirName.IndexOf(verName));
                    if (systemName.EndsWith("."))
                        systemName = systemName.Substring(0, systemName.Length - 1);

                    BrancheInfo ver;
                    if (!versions.ContainsKey(verName))
                    {
                        ver = new BrancheInfo { VersionName = verName, Path = path };
                        versions.Add(verName, ver);
                    }
                    else
                    {
                        ver = versions[verName];
                    }

                    SystemInfo system;
                    if (!ver.Systems.ContainsKey(systemName))
                    {
                        system = new SystemInfo { SystemName = systemName, Path = dir };
                        ver.Systems.Add(systemName, system);
                    }
                    else
                    {
                        system = ver.Systems[systemName];
                    }
                        
                }
                else
                {
                    level++;
                    if (level <= maxLevel)
                        GetVersions(dir, versions, level, maxLevel);
                }
            }
        }

        public static List<FileInfo> GetFiles(string path, SearchOption searchOption = SearchOption.AllDirectories, params string[] extensions)
        {
            List<FileInfo> list = new List<FileInfo>();
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (var extension in extensions)
            {
                FileInfo[] files = dir.GetFiles(extension, searchOption);
                list.AddRange(files);
            }
            return list;
        }

        public static bool Contains(string path, string search, bool toLower)
        {
            if (toLower)
                return File.ReadAllText(path).ToLower().Contains(search);
            else 
                return File.ReadAllText(path).Contains(search);
        }

        /// <summary>
        /// Compara as duas datas se são diferentes.
        /// Usa o Ticks, e checa se a diferença é maior que 20000.
        /// </summary>
        /// <param name="d1"></param>
        /// <param name="d2"></param>
        /// <returns></returns>
        public static bool HasChanged(DateTime d1, DateTime d2)
        {
            //return Math.Abs(d1.Ticks - d2.Ticks) > 20000;
            return d1.ToString("dd/MM/yy HH:mm:ss") != d2.ToString("dd/MM/yy HH:mm:ss");
        }

        /// <summary>
        /// Retorna o caminho absoluto de um arquivo
        /// </summary>
        /// <param name="dir">Diretório de onde se refere o caminho relativo</param>
        /// <param name="relativePath">caminho relativo</param>
        /// <returns></returns>
        public static string GetAbsolutePath(string dir, string relativePath)
        {
            relativePath = relativePath.Replace("/", @"\");
            while (relativePath.StartsWith(@"\"))
                relativePath = relativePath.Substring(0, relativePath.Length - 1);

            var path = System.IO.Path.Combine(dir, relativePath);
            var f = new System.IO.FileInfo(path);
            return f.FullName;

        }

    }

    /// <summary>
    /// Classe base usada pelos nodes tipados
    /// </summary>
    public class DataInfo
    {

        public string Path { get; set; }
        public string Text { get; set; }

        public DataInfo()
        {
        }
        public DataInfo(string text, string path = null)
        {
            this.Text = text;
            this.Path = path;
        }

    }

    public class BrancheInfo : DataInfo
    {

        public string VersionName { get; set; }

        public Dictionary<string, SystemInfo> Systems { get; set; }

        public BrancheInfo()
        {
            Systems = new Dictionary<string, SystemInfo>(StringComparer.InvariantCultureIgnoreCase);
        }

        public override string ToString()
        {
            return string.Format("{0} - {1}", VersionName, Path);
        }

    }

    public class SystemInfo : DataInfo
    {

        public string SystemName { get; set; }

        public override string ToString()
        {
            return string.Format("{0} - {1}", SystemName, Path);
        }

     }
}

